<template>
  <div class="w-100vw flex flex-col flex-center mt-50px mb-20px">
    <div class="flex flex-center" @click="toHome">
      <img src="../../assets/logo.png" class="w-2rem" />
      <span class="text-2em ml-0.5rem font-bold">RCEP</span>
    </div>
    <!-- <div class="border p-10px mt-20px"></div> -->
    <el-card class="mt-20px min-w-300px max-w-90vw">
      <div>
        <div class="flex justify-between w-full">
          <span class="text-1.5em font-bold"> 创建账户 </span>
          <el-button type="defalut" @click="$router.push('/')">返回主页</el-button>
        </div>
        <el-form
          ref="formRef"
          label-position="top"
          class="mt-20px"
          :rules="rules"
          :model="formData"
        >
          <el-form-item label="您的姓名" prop="username">
            <el-input placeholder="输入姓名" v-model="formData.username" />
          </el-form-item>
          <el-form-item label="邮箱或手机号码" prop="loginAccount">
            <el-input placeholder="输入邮箱或手机号码" v-model="formData.loginAccount">
              <template #append>
                <div @click="sendCode">
                  {{ secondTime !== 60 ? secondTime + 's' : '发送验证码' }}
                </div>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="code">
            <el-input placeholder="输入验证码" v-model="formData.code" />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
              placeholder="输入密码"
              v-model="formData.password"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="repPassword">
            <el-input
              placeholder="确认密码"
              v-model="formData.repPassword"
              type="password"
              show-password
            />
          </el-form-item>

          <el-checkbox
            v-model="isAgree"
            :label="'我已阅读并同意网站的使用条件及隐私声明'"
            true-label="1"
            false-label="0"
          />
        </el-form>
        <div class="my-0.8em text-0.9em w-full">
          注册手机号码即表示您同意接收RCEP通过短信自动发送的安全通知。您可以进入“我的账户”设置，在“登录与安全”页面移除您的手机号码以选择退出。可能会收取短信和数据费用。
        </div>
        <div class="mt-1em">
          <el-button type="warning" class="w-full !font-bold" @click="submit" :loading="loading">
            注册
          </el-button>
        </div>
      </div>
      <el-divider />
      <div class="w-full">
        已有账户？<a href="javascript:;" class="text-blue" @click="$router.push('/login')">登录</a>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { postRegister, sendSmsCode, sendEmailCode, postLogin } from '@/api/member'
import { setCookie, isValidEmail, isValidPhone } from '@/utils/index'
import { useRouter } from 'vue-router'
const router = useRouter()
const formRef = ref()
const isAgree = ref(true)
const loading = ref(false)
const secondTime = ref(60)

const formData = reactive({
  username: null,
  password: null,
  code: null,
  password: null,
  repPassword: null,
  loginAccount: null,
})
const rules = {
  username: [{ required: true, message: '请输入姓名', trigger: 'change' }],
  loginAccount: [
    { required: true, message: '请输入邮箱或手机号码', trigger: 'change' },
    {
      validator(rule, value, callback) {
        if (!isValidEmail(value) && !isValidPhone(value)) {
          callback(new Error('格式不正确'))
        } else {
          callback()
        }
      },
    },
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'change' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 6, max: 30, message: '密码至少为6个字符' },
    {
      validator: (rule, value, callback) => {
        const reg = /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/
        if (!reg.test(value)) {
          callback('密码必须为大小写字母+数字组合')
        } else {
          callback()
        }
      },
    },
  ],
  repPassword: [
    { required: true, message: '请输入密码', trigger: 'change' },
    {
      validator(rule, value, callback) {
        if (value !== formData.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      },
    },
  ],
}

const toHome = () => {
  router.push('/')
}

const sendCode = () => {
  formRef.value.validateField('loginAccount', (valid) => {
    if (valid) {
      if (!isValidEmail(formData.loginAccount)) {
        sendSmsCode({
          mobile: formData.loginAccount,
        }).then((res) => {
          if (res.code === 20000) {
            countTime()
          }
        })
      } else {
        sendEmailCode({
          email: formData.loginAccount,
        }).then((res) => {
          if (res.code === 20000) {
            countTime()
          }
        })
      }
    }
  })
}

const countTime = () => {
  secondTime.value--
  if (secondTime.value > 0) {
    setTimeout(() => {
      countTime()
    }, 1000)
  } else {
    secondTime.value = 60
  }
}

const submit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      let obj = {}
      if (!isValidEmail(formData.loginAccount)) {
        obj = { mobile: formData.loginAccount, registerType: 1 }
      } else {
        obj = { email: formData.loginAccount, registerType: 2 }
      }
      postRegister({
        ...obj,
        username: formData.username,
        password: formData.password,
        repPassword: formData.repPassword,
        code: formData.code,
      }).then((res) => {
        if (res.code === 20000) {
          postLogin({
            loginAccount: formData.loginAccount,
            password: formData.password,
          }).then(({ code, data }) => {
            if (code === 20000) {
              ElMessage({
                type: 'success',
                message: '注册成功',
              })
              setCookie('token', data.data.access_token, import.meta.env.VITE_DOMAIN_URL, false)
              router.push('/')
            }
          })
        }
      })
    }
  })
}
</script>

<style lang="scss" scoped>
:deep .el-form-item {
  margin-bottom: 1em;
}
:deep .el-form-item__label {
  font-weight: 700;
}
input {
  box-shadow: none;
  border: 1px solid #ccc; /* 可选：自定义边框样式 */
}

.logo {
  margin-right: 12px;
  width: 18px;
  height: 18px;
  overflow: hidden;
  background-image: url('@//assets/image/app-logo.png');
  background-repeat: no-repeat;
  background-position: -36px 0px;
}
</style>
